<template>
  <div class="article-detail-container">
    <div v-loading="loading" class="article-detail">
      <!-- 文章头部 -->
      <div class="article-header">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/article' }">文章中心</el-breadcrumb-item>
            <el-breadcrumb-item>{{ articleInfo.categoryName }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ articleInfo.title }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <h1 class="article-title">{{ articleInfo.title }}</h1>
        
        <div class="article-meta">
          <div class="meta-left">
            <el-avatar :size="40" :src="articleInfo.authorAvatar" />
            <div class="author-info">
              <div class="author-name">{{ articleInfo.author }}</div>
              <div class="publish-info">
                <span>{{ formatTime(articleInfo.publishTime) }}</span>
                <span class="separator">·</span>
                <span>{{ articleInfo.readTime }}分钟阅读</span>
              </div>
            </div>
          </div>
          <div class="meta-right">
            <div class="article-stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ articleInfo.viewCount }}
              </span>
              <span class="stat-item">
                <el-icon><Star /></el-icon>
                {{ articleInfo.likeCount }}
              </span>
              <span class="stat-item">
                <el-icon><ChatDotRound /></el-icon>
                {{ articleInfo.commentCount }}
              </span>
            </div>
            <div class="article-actions">
              <el-button 
                :type="isLiked ? 'danger' : 'default'"
                @click="toggleLike"
                :icon="isLiked ? 'StarFilled' : 'Star'"
              >
                {{ isLiked ? '已点赞' : '点赞' }}
              </el-button>
              <el-button 
                :type="isFavorited ? 'warning' : 'default'"
                @click="toggleFavorite"
                :icon="isFavorited ? 'CollectionFilled' : 'Collection'"
              >
                {{ isFavorited ? '已收藏' : '收藏' }}
              </el-button>
              <el-button @click="shareArticle" icon="Share">分享</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 文章内容 -->
      <div class="article-content">
        <div class="content-body" v-html="articleInfo.content"></div>
        
        <!-- 文章标签 -->
        <div class="article-tags">
          <el-tag 
            v-for="tag in articleInfo.tags"
            :key="tag"
            size="large"
            style="margin-right: 8px; margin-bottom: 8px;"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comment-section">
        <div class="comment-header">
          <h3>评论 ({{ comments.length }})</h3>
          <div class="comment-sort">
            <el-radio-group v-model="commentSort" @change="loadComments">
              <el-radio-button value="latest">最新</el-radio-button>
              <el-radio-button value="hottest">最热</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 发表评论 -->
        <div class="comment-form">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="4"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
          />
          <div class="comment-actions">
            <el-button type="primary" @click="submitComment" :disabled="!commentContent.trim()">
              发表评论
            </el-button>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div 
            v-for="comment in comments"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-avatar">
              <el-avatar :size="40" :src="comment.userAvatar" />
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.username }}</span>
                <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>
              <div class="comment-actions">
                <el-button 
                  type="text" 
                  size="small"
                  @click="toggleCommentLike(comment)"
                  :class="{ 'is-liked': comment.isLiked }"
                >
                  <el-icon><Star /></el-icon>
                  {{ comment.likeCount || 0 }}
                </el-button>
                <el-button type="text" size="small" @click="replyComment(comment)">
                  回复
                </el-button>
              </div>
              
              <!-- 回复列表 -->
              <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
                <div 
                  v-for="reply in comment.replies"
                  :key="reply.id"
                  class="reply-item"
                >
                  <el-avatar :size="24" :src="reply.userAvatar" />
                  <div class="reply-content">
                    <span class="reply-author">{{ reply.username }}</span>
                    <span class="reply-text">{{ reply.content }}</span>
                    <span class="reply-time">{{ formatTime(reply.createTime) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多评论 -->
        <div v-if="hasMoreComments" class="load-more-comments">
          <el-button @click="loadMoreComments" :loading="loadingComments">
            加载更多评论
          </el-button>
        </div>
      </div>

      <!-- 相关文章 -->
      <div class="related-articles">
        <h3>相关文章</h3>
        <div class="article-grid">
          <div 
            v-for="article in relatedArticles"
            :key="article.id"
            class="related-article-card"
            @click="goToArticle(article.id)"
          >
            <el-image
              :src="article.coverImage || '/default-article.jpg'"
              fit="cover"
              class="article-cover"
            />
            <div class="article-info">
              <h4>{{ article.title }}</h4>
              <p>{{ article.summary }}</p>
              <div class="article-meta">
                <span>{{ article.author }}</span>
                <span>{{ formatTime(article.publishTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getArticleDetail,
  likeArticle,
  favoriteArticle,
  getArticleComments,
  submitArticleComment,
  likeComment,
  getRelatedArticles
} from '@/api/article'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const loadingComments = ref(false)
const articleInfo = ref({})
const comments = ref([])
const relatedArticles = ref([])
const commentContent = ref('')
const commentSort = ref('latest')
const isLiked = ref(false)
const isFavorited = ref(false)
const hasMoreComments = ref(true)

// 获取文章详情
const loadArticleDetail = async () => {
  try {
    const response = await getArticleDetail(route.params.id)
    if (response.code === 200) {
      articleInfo.value = response.data
      isLiked.value = response.data.isLiked
      isFavorited.value = response.data.isFavorited
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  }
}

// 获取评论列表
const loadComments = async () => {
  loadingComments.value = true
  try {
    const response = await getArticleComments(route.params.id, {
      sort: commentSort.value,
      page: 1,
      size: 20
    })
    if (response.code === 200) {
      comments.value = response.data.records || []
      hasMoreComments.value = response.data.hasMore
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  } finally {
    loadingComments.value = false
  }
}

// 获取相关文章
const loadRelatedArticles = async () => {
  try {
    const response = await getRelatedArticles(route.params.id)
    if (response.code === 200) {
      relatedArticles.value = response.data
    }
  } catch (error) {
    console.error('获取相关文章失败:', error)
  }
}

// 点赞文章
const toggleLike = async () => {
  try {
    await likeArticle(route.params.id, !isLiked.value)
    isLiked.value = !isLiked.value
    if (isLiked.value) {
      articleInfo.value.likeCount++
      ElMessage.success('点赞成功')
    } else {
      articleInfo.value.likeCount--
      ElMessage.success('取消点赞')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 收藏文章
const toggleFavorite = async () => {
  try {
    await favoriteArticle(route.params.id, !isFavorited.value)
    isFavorited.value = !isFavorited.value
    ElMessage.success(isFavorited.value ? '收藏成功' : '取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分享文章
const shareArticle = () => {
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) return
  
  try {
    const response = await submitArticleComment(route.params.id, {
      content: commentContent.value
    })
    if (response.code === 200) {
      ElMessage.success('评论发表成功')
      commentContent.value = ''
      loadComments()
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  }
}

// 点赞评论
const toggleCommentLike = async (comment) => {
  try {
    await likeComment(comment.id, !comment.isLiked)
    comment.isLiked = !comment.isLiked
    if (comment.isLiked) {
      comment.likeCount = (comment.likeCount || 0) + 1
    } else {
      comment.likeCount = Math.max((comment.likeCount || 0) - 1, 0)
    }
  } catch (error) {
    console.error('点赞评论失败:', error)
    ElMessage.error('操作失败')
  }
}

// 回复评论
const replyComment = (comment) => {
  ElMessage.info('回复功能开发中...')
}

// 加载更多评论
const loadMoreComments = () => {
  ElMessage.info('加载更多功能开发中...')
}

// 跳转到文章
const goToArticle = (articleId) => {
  router.push(`/article/${articleId}`)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleDateString()
}

// 页面加载
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadArticleDetail(),
      loadComments(),
      loadRelatedArticles()
    ])
  } finally {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.article-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.article-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  min-height: 100vh;
}

.article-header {
  margin-bottom: 32px;
  
  .breadcrumb {
    margin-bottom: 16px;
  }
  
  .article-title {
    font-size: 32px;
    font-weight: 700;
    line-height: 1.4;
    margin: 0 0 24px 0;
    color: #1a1a1a;
  }
  
  .article-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #eee;
    
    .meta-left {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .author-info {
        .author-name {
          font-weight: 600;
          margin-bottom: 4px;
        }
        
        .publish-info {
          font-size: 14px;
          color: #666;
          
          .separator {
            margin: 0 8px;
          }
        }
      }
    }
    
    .meta-right {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 12px;
      
      .article-stats {
        display: flex;
        gap: 16px;
        
        .stat-item {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #666;
          font-size: 14px;
        }
      }
      
      .article-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
}

.article-content {
  margin-bottom: 48px;
  
  .content-body {
    line-height: 1.8;
    font-size: 16px;
    color: #333;
    margin-bottom: 24px;
    
    :deep(img) {
      max-width: 100%;
      height: auto;
      margin: 16px 0;
    }
    
    :deep(p) {
      margin-bottom: 16px;
    }
    
    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin: 24px 0 16px 0;
      font-weight: 600;
    }
  }
  
  .article-tags {
    padding-top: 24px;
    border-top: 1px solid #eee;
  }
}

.comment-section {
  margin-bottom: 48px;
  
  .comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h3 {
      margin: 0;
    }
  }
  
  .comment-form {
    margin-bottom: 32px;
    
    .comment-actions {
      margin-top: 12px;
      text-align: right;
    }
  }
  
  .comment-list {
    .comment-item {
      display: flex;
      gap: 12px;
      margin-bottom: 24px;
      
      .comment-content {
        flex: 1;
        
        .comment-header {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 8px;
          
          .comment-author {
            font-weight: 600;
          }
          
          .comment-time {
            color: #666;
            font-size: 14px;
          }
        }
        
        .comment-text {
          line-height: 1.6;
          margin-bottom: 12px;
        }
        
        .comment-actions {
          display: flex;
          gap: 16px;
          
          .is-liked {
            color: #f56c6c;
          }
        }
        
        .reply-list {
          margin-top: 16px;
          padding-left: 16px;
          border-left: 2px solid #f0f0f0;
          
          .reply-item {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            
            .reply-content {
              flex: 1;
              font-size: 14px;
              
              .reply-author {
                font-weight: 600;
                margin-right: 8px;
              }
              
              .reply-time {
                color: #666;
                margin-left: 8px;
              }
            }
          }
        }
      }
    }
  }
  
  .load-more-comments {
    text-align: center;
    margin-top: 24px;
  }
}

.related-articles {
  h3 {
    margin-bottom: 20px;
  }
  
  .article-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
  }
  
  .related-article-card {
    border: 1px solid #eee;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.3s, box-shadow 0.3s;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
    
    .article-cover {
      width: 100%;
      height: 120px;
    }
    
    .article-info {
      padding: 12px;
      
      h4 {
        margin: 0 0 8px 0;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      p {
        margin: 0 0 8px 0;
        color: #666;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      
      .article-meta {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        color: #999;
      }
    }
  }
}

@media (max-width: 768px) {
  .article-detail {
    padding: 12px;
  }
  
  .article-title {
    font-size: 24px !important;
  }
  
  .article-meta {
    flex-direction: column !important;
    align-items: flex-start !important;
    gap: 16px;
    
    .meta-right {
      align-items: flex-start !important;
    }
  }
  
  .article-grid {
    grid-template-columns: 1fr !important;
  }
}
</style>
